package com.wsz.bot.service.impl;

import com.wsz.pojo.Cell;
import com.wsz.pojo.dto.BotDto;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Bot implements java.util.function.Supplier<Integer> {

    public List<Cell> getCell(int sx, int sy,List<Integer> steps){
        List<Cell> res = new ArrayList<>();

        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};

        int x = sx, y = sy,tmp = 0;

        res.add(new Cell(x,y));

        for(int d : steps){
            x += dx[d];
            y += dy[d];

            res.add(new Cell(x,y));

            if(!check_len(++tmp)){
                res.remove(0);
            }
        }
        return res;
    }

    private Boolean check_len(int step){
        if(step <= 10) return true;
        return (step - 10) % 3 == 0;
    }

    public Integer nextMove(BotDto botDto) {
        int [][]g = botDto.getG();

        int aSx = botDto.getX();int aSy = botDto.getY();
        int bSX = botDto.getSx();int bSy = botDto.getSy();


        List<Cell> aCells = getCell(aSx,aSy,botDto.getStep1());
        List<Cell> bCells = getCell(bSX, bSy, botDto.getStep2());

        for(Cell c : aCells) g[c.getX()][c.getY()] = 1;
        for(Cell c : bCells) g[c.getX()][c.getY()] = 1;

        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};

        for (int i = 0; i < 4; i++) {
            int x = aCells.get(aCells.size() - 1).getX() + dx[i];
            int y = aCells.get(aCells.size() - 1).getY() + dy[i];
            if(x >= 0 && x < 13 && y >= 0 && y < 14 && g[x][y] == 0){
                return i;
            }
        }
        return 0;
    }

    @Override
    public Integer get() {
        File file = new File("input.text");

        try{
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois;
            try (BufferedInputStream bis = new BufferedInputStream(fis)) {
                /* ------读取->反序列化------- */
                ois = new ObjectInputStream(bis);
                BotDto botDto = (BotDto) ois.readObject(); // 读取一个类
                System.out.println(botDto.getUserId() + botDto.getX() + botDto.getY());
                return nextMove(botDto);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }
}
